package com.tanger.common.service;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanger.common.page.PageBean;
import com.tanger.common.page.PageList;
import com.tanger.common.page.QueryFilter;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

public class BaseServiceImpl<M extends BaseMapper<T>, T extends Model<T>> extends ServiceImpl<M, T> implements BaseService<T>, QueryFilterHelper<T> {
	@Override
	public T get(Serializable id) {
		return this.getById(id);
	}

	@Override
	public void create(T t) {
		this.save(t);
	}

	@Override
	public void update(T t) {
		this.updateById(t);
	}

	@Override
	public void delete(Serializable id) {
		this.removeById(id);
	}
	
	@Override
	public void deleteByIds(String ...ids) {
		this.removeByIds(Arrays.asList(ids));
	}
	
	@Override
	@Transactional(readOnly=true)
	public PageList<T> findAllPage(QueryFilter<T> queryFilter) {
		M mapper = super.getBaseMapper();
		IPage<T> result = mapper.selectPage(convert2IPage(queryFilter.getPageBean()), convert2Wrapper(queryFilter, currentModelClass()));
		return new PageList<T>(result);
	}
	
	@Override
	public PageList<T> findAll(PageBean pageBean) {
		IPage<T> result = this.page(convert2IPage(pageBean));
		return new PageList<T>(result);
	}

	@Override
	public List<T> getAll() {
		return Optional.ofNullable(this.list()).orElseGet(Collections::emptyList);
	}

	@Override
	@Transactional(readOnly=true)
	public List<T> findAll(QueryFilter<T> queryFilter) {
		M mapper = super.getBaseMapper();
		return Optional.ofNullable(mapper.selectList(convert2Wrapper(queryFilter, currentModelClass())))
				.orElseGet(Collections::emptyList);
	}
}
